// 当前页
let currentPage = 0

// 一页显示多少条
const pageSize = 10

// 当前搜索条件
const currentSearch = {
    title: '',
    category_id: ''
}

// 获取分类
async function getCategory() {
    const res = await $.ajax({
        url: 'http://localhost:8081/api/getCategory.php',
        type: 'get'
    })
    return res
}

// 渲染分类
async function renderCategory() {
    const select = document.querySelector('.header .search select')
    const fragment = document.createDocumentFragment()
    const categoryData = await getCategory()
    if (categoryData.code === 1) {
        categoryData.data.forEach(item => {
            const option = document.createElement('option')
            option.value = item.id
            option.innerHTML = item.name
            fragment.appendChild(option)
        })
        select.appendChild(fragment)
    }
}
renderCategory()

// 搜索
document.querySelector('.header .search .search-btn').addEventListener('click', function () {
    const input = document.querySelector('.header .search input').value
    const select = document.querySelector('.header .search select').value
    currentSearch.title = input
    currentSearch.category_id = select
    currentPage = 0
    renderArticle(1, currentSearch.title, currentSearch.category_id)
})


// 获取文章
async function getArticleRequest(data) {
    const res = await $.ajax({
        url: 'http://localhost:8081/api/getArticle.php',
        type: 'get',
        data: data,
    })
    return res
}

// 渲染文章
async function renderArticle(page = 1, title = null, category_id = null) {
    const articleList = document.querySelector('.main .article-list');
    const fragment = document.createDocumentFragment()
    articleList.innerHTML = ''

    const articleData = await getArticleRequest({
        page,
        pageSize,
        title,
        category_id
    });
    document.querySelector('.main .sidebar .sidebar-main .num i').innerHTML = articleData.total

    if (articleData.code === 1) {
        renderPaginator(articleData, pageSize, currentPage + 1)
        articleData.data.forEach(item => {
            const li = document.createElement('li')
            li.className = 'article-item'
            li.innerHTML = `
                <div class="article-head">
                    <span class="name">${item.username}</span>
                    <span class="tiem">${diffForHumans(item.update_at)}</span>
                </div>
                <div class="article-main">
                    <h2 class="title text-ellipsis-1"><a href="../article/article.php?id=${item.id}">${item.title}</a></h2>
                    <p class="content text-ellipsis-4">${item.content}</p>
                </div>
                <div class="article-footer">
                    <div class="tag">${item.category}</div>
                </div>
            `
            fragment.appendChild(li)
        })
        articleList.appendChild(fragment)
    }
}
renderArticle()

// 渲染分页器
function renderPaginator(articleData, pageSize, currentPage) {
    const paginator = document.querySelector('.article-box .paginator')
    paginator.innerHTML = '<button class="prev-next prev"><</button><button class="prev-next next">></button>'
    const next = paginator.querySelector('.next')
    const prev = paginator.querySelector('.prev')
    const total = Math.ceil(articleData.total / pageSize)

    for (let i = 1; i <= total; i++) {
        const div = document.createElement('div')
        div.className = 'num'
        if (i === currentPage) {
            div.classList.add('active')
        }
        div.innerHTML = i
        paginator.insertBefore(div, next)
    }

    // 判断是否禁用上一页或禁用下一页
    prev.disabled = currentPage <= 1
    next.disabled = currentPage >= total
}

// 点击分页渲染相应的位置
$('.paginator').click(function (e) {
    // 点击页数
    if (e.target.classList.contains('num')) {
        const currentNum = document.querySelector('.paginator .active');
        if (currentNum) currentNum.classList.remove('active')
        e.target.classList.add('active')
        const page = e.target.innerHTML
        currentPage = page - 1
        renderArticle(page, currentSearch.title, currentSearch.category_id)
    }

    // 点击上一页
    if (e.target.classList.contains('prev')) {
        prevAndNext(currentPage - 1)
    }

    if (e.target.classList.contains('next')) {
        prevAndNext(currentPage + 1)
    }
})

// 上一页和下一页
function prevAndNext(index) {
    const currentNum = document.querySelector('.paginator .active');
    if (currentNum) currentNum.classList.remove('active')
    const numList = document.querySelectorAll('.paginator .num')
    numList[index].classList.add('active')
    const page = numList[index].innerHTML
    currentPage = index
    renderArticle(page, currentSearch.title, currentSearch.category_id)
}